from openai import OpenAI
import os
from shared import logging

# 初始化日志
logger = logging.getLogger(__name__)

class ChatBot:
    def __init__(self):
        """初始化 ChatBot"""
        self.api_key = os.getenv('DEEPSEEK_API_KEY')
        if not self.api_key:
            raise ValueError("未设置 DEEPSEEK_API_KEY 环境变量")
            
        self.client = OpenAI(
            api_key=self.api_key, 
            base_url="https://api.deepseek.com"
        )
        self.messages = []  # 存储对话历史

    def chat(self, input_text):
        """
        与 AI 进行对话
        :param input_text: 用户输入的文本
        :return: AI 的回复文本
        """
        # 添加用户消息
        self.messages.append({
            "role": "user",
            "content": input_text
        })

        # 限制对话历史长度
        if len(self.messages) > 10:
            self.messages.pop(0)
        # 打印对话历史 
        logger.debug(f"当前对话历史 ({len(self.messages)} 条消息):")

        try:
            # 获取 AI 回复
            response = self.client.chat.completions.create(
                model="deepseek-chat",
                messages=self.messages,
                stream=False
            )

            # 提取回复内容
            reply = response.choices[0].message.content

            # 保存 AI 回复到对话历史
            self.messages.append({
                "role": "assistant",
                "content": reply
            })

            return reply

        except Exception as e:
            print(f"对话出错: {str(e)}")
            return None

    def reset_conversation(self):
        """重置对话历史"""
        self.messages = []